package com.thinkingstar.iads.datacenter.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.bstek.urule.runtime.response.RuleExecutionResponse;
import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;
import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import com.thinkingstar.iads.common.uploadFile.vo.UploadFileInfoVO;
import com.thinkingstar.iads.common.utils.DownloadFileUtil;
import com.thinkingstar.iads.common.utils.POIFileUtil;
import com.thinkingstar.iads.common.utils.PictureUtil;
import com.thinkingstar.iads.common.utils.StringUtil;
import com.thinkingstar.iads.datacenter.entity.DcEquipmentEquipInfo;
import com.thinkingstar.iads.datacenter.entity.DcManufacturerEquipmentField;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcEquipmentEquip;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcEquipmentEquipInfo;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectEquipmentField;
import com.thinkingstar.iads.projectcenter.entity.PcProjectEquipmentEquip;
import com.thinkingstar.iads.projectcenter.entity.PcProjectEquipmentEquipInfo;
import com.thinkingstar.iads.projectcenter.entity.PcProjectFile;
import com.thinkingstar.iads.projectcenter.entity.PcProjectInfo;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcEquipmentEquip;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectData;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectEquipmentEquipInfo;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectFile;


@IocBean
@At("/datacenter/common")
@Filters({ @By(type = GlobalsFilter.class), @By(type = UserLoginFilter.class) })
public class BusinessDataCommonManagerController {
	
	private static Log log = Logs.get();
	
	@Inject
	private DaoPcProjectFile daoPcProjectFile;
	
	@Inject
	private DaoPcProjectData daoPcProjectData;
	
	@Inject
	private DaoDcEquipmentEquip daoDcEquipmentEquip;
	
	@Inject
	private DaoDcEquipmentEquipInfo daoDcEquipmentEquipInfo;
	
	@Inject
	private DaoPcEquipmentEquip daoPcEquipmentEquip;
	
	@Inject
	private DaoPcProjectEquipmentEquipInfo daoPcProjectEquipmentEquipInfo;
	
	@Inject
	private DaoDcProjectEquipmentField daoDcProjectEquipmentField;
	
	private HashMap<String, HashMap<String , List<String>>> equipment_file_recode = null; //保存文件记录信息
	
	
	//多文件上传
	@At("/fileinput/?")
	@Ok("beetl:/projectRoot/dcCenter/common/fileinput.html")
	public NutMap fileinput(String equipment_id){
		DcManufacturerEquipmentField object = daoDcProjectEquipmentField.findObjByManfacturerEquipmentId(equipment_id);
		if(object != null){
			return new NutMap("data",object).addv("manfacturer_equipment_id", equipment_id);
		}
		return new NutMap("manfacturer_equipment_id",equipment_id);
	}
	
	//获取图片文件流
	@At("/getImage")
	public void getImage(@Param("file_name") String relative_path,HttpServletRequest request , HttpServletResponse response){
		String file_path = POIFileUtil.getAbFileNameByRepath(relative_path);
		File file = new File(file_path);
		String file_name = StringUtil.getFileNameByPath(relative_path);
		DownloadFileUtil.downLoadFile(file, file_name, request, response);
	}
	
	//获取文件
	@At("/getFileById")
	public void getFileById(@Param("file_id") String file_id , HttpServletRequest request , HttpServletResponse response){
		PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
		if(pcProjectFile != null){
			String relative_path = pcProjectFile.getRelativePaths();
			String file_path = POIFileUtil.getAbFileNameByRepath(relative_path);
			File file = new File(file_path);
			String file_name = pcProjectFile.getName();
			DownloadFileUtil.downLoadFile(file, file_name, request, response);
		}
	}
	
	@At("/getFileStream")
	public void getFileStream(@Param("file_id") String file_id , HttpServletRequest request , HttpServletResponse response){
		PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
		if(pcProjectFile != null){
			String relative_path = pcProjectFile.getRelativePaths();
			String file_path = POIFileUtil.getAbFileNameByRepath(relative_path);
			DownloadFileUtil.fileStream(file_path, request, response);
		}
	}

	
/*	*//**
	 * 根据文件路径删除文件
	 * @param file_path 已有的文件路径
	 * @return
	 *//*
	@At("/delFileById/?/?")
	@Ok("json")
	public Object delFileById(String file_id , String field_name){
		List <String> field_ids = file_upload_record.get(field_name);
		Boolean boolean1 = field_ids.remove(file_id);
		PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
		String ab_file_path = POIFileUtil.getAbFileNameByRepath(pcProjectFile.getRelativePaths());
		Boolean boolean2 = PictureUtil.removeFile(ab_file_path);
		try {
			if(boolean1 && boolean2){
				return new NutMap("msg","文件删除成功!").addv("code", "200").addv("data", getStrByList(file_upload_record.get(field_name))).addv("field_name", field_name);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new NutMap("msg","删除失败,系统异常!").addv("code", "500");
		}
		return new NutMap("msg","删除失败!").addv("code", "500");
	}*/
	
	public static String getStrByList(List <String> list){
		String strs = "";
		for(int i=0;i<list.size();i++){
			if(i == list.size()-1){
				strs += list.get(i);
			}else{
				strs += list.get(i)+",";
			}
		}
		return strs;
	}
	
	//根据id返回文件详细信息(文件预览以及删除使用)
	@At("/findFileInfoById/?/?")
	@Ok("json")
	public Object findFileInfoById(String file_id , String field_name ,  HttpServletRequest request){
		NutMap nutMap = new NutMap("key",file_id);
		PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
		nutMap.addv("caption", pcProjectFile.getName()).addv("url", request.getContextPath()+"/datacenter/common/delFileById/"+file_id+"/"+field_name);
		return nutMap;
	}
	
	
	@At("/findFileInfoById/?")
	@Ok("json")
	public Object findFileInfoById(String file_id ,  HttpServletRequest request){
		NutMap nutMap = new NutMap("key",file_id);
		PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
		nutMap.addv("caption", pcProjectFile.getName());
		return nutMap;
	}
	
	//多文件上传
	@At("/multifileUploadFile")
	@Ok("json")
	public Object multifileUploadFile(@Param("..") NutMap param , HttpServletRequest request){
		if(param == null){
			return new NutMap("msg","上传失败!").addv("code", "500");
		}
		String field_name = param.getString("field_name");//文件组
		String file_kind = param.getString("file_kind"); //文件归属
		String equipment_id = param.getString("equipment_id"); //设备id
		List <String> file_ids = new ArrayList<String>();
		//设备资料信息为空
		if(equipment_file_recode == null || equipment_file_recode.get(equipment_id) == null){
			//保存新设备信息
			equipment_file_recode = new HashMap<>();
			HashMap<String, List<String>> file_upload_record = new HashMap<>();
			file_upload_record.put(field_name, file_ids);
			equipment_file_recode.put(equipment_id, file_upload_record);
		}else{
			HashMap<String, List<String>> file_upload_record = equipment_file_recode.get(equipment_id);
			if(!file_upload_record.isEmpty() && file_upload_record.get(field_name) != null){
				file_ids = file_upload_record.get(field_name);
			}else{
				file_upload_record.put(field_name, file_ids);
			}
		}
	    MultipartFile multipartFile = null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);//判断是否是文件提交
		if(isMultipart){
        	ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        	CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        	MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest()); 
        	multipartFile = multipartRequest.getFile("file");
    		InputStream fileStream;
    		try {
				fileStream = multipartFile.getInputStream();
    			String upload_file_name = multipartFile.getOriginalFilename();//本地文件名称
    			String suffix_name = upload_file_name.substring(upload_file_name.indexOf(".")+1);//后缀名
    			//String new_file_name = PictureUtil.createFileName(suffix_name);//新文件名
    			String re_file_path = POIFileUtil.getFileName(upload_file_name,suffix_name,file_kind);//文件相对路径
    			String full_file_name = POIFileUtil.getAbFileNameByRepath(re_file_path); //绝对路径
    			Boolean is_success = PictureUtil.storeFile(fileStream, full_file_name);
				if(is_success){
					String file_id = daoPcProjectFile.saveFile(re_file_path,upload_file_name);
					file_ids.add(file_id);
					return new NutMap("msg","文件上传成功!").addv("code", "200").addv("data", getStrByList(equipment_file_recode.get(equipment_id).get(field_name))).addv("field_name", field_name);
				}
			} catch (IOException e) {
				e.printStackTrace();
				return new NutMap("msg","上传失败,系统异常!").addv("code", "500");
			}
		}
		return new NutMap("msg","上传失败!").addv("code", "500");
	}
	
	//下载设备文件
	@At("/downFileById/?/?")
	public void getFileById(String type , String equipment_id , HttpServletRequest request , HttpServletResponse response){
		DcManufacturerEquipmentField equipment_field = daoDcProjectEquipmentField.findObjByManfacturerEquipmentId(equipment_id);
		if(equipment_field != null){
			String file_ids = "";
			if("sbzp".equals(type)){
				file_ids = equipment_field.getEquipment_photo();
			}else if("tjtjt".equals(type)){
				file_ids = equipment_field.getEquipment_tjtjt();
			}else if("yhxqs".equals(type)){
				file_ids = equipment_field.getEquipment_yhxqs();
			}else if("jsjk".equals(type)){
				file_ids = equipment_field.getEquipment_jsjk();
			}else if("bimodel".equals(type)){
				file_ids = equipment_field.getEquipment_bim_model();
			}
			if(StringUtils.isNotBlank(file_ids)){
				String [] strings = file_ids.split(",");
				List<File> list = new ArrayList<>();
				for(int i=0;i<strings.length;i++){
					String file_id = strings[i];
					PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
					if(pcProjectFile != null){
						String relative_path = pcProjectFile.getRelativePaths();
						String file_path = POIFileUtil.getAbFileNameByRepath(relative_path);
						File file = new File(file_path);
						list.add(file);
					}
				}
				String zip_name = PictureUtil.createFileName("zip");
				String re_path = POIFileUtil.getFileName(zip_name, "zip", "zip");
				String ab_path = POIFileUtil.getAbFileNameByRepath(re_path);
				Boolean bool = POIFileUtil.writeZip(list, ab_path);
				if(bool){
					DownloadFileUtil.downLoadFile(new File(ab_path), zip_name, request, response);
				}
			
				
			}

		}
		

	}
	
	
	//单文件上传公用方法
	@At("/uploadFile")
	@Ok("json")
	public Object uploadFile(HttpServletRequest request , @Param("file_kind") String file_kind){
		NutMap data_map = null;
		MultipartFile file=null;
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    	if(isMultipart){
        	ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        	CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        	MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest()); 
        	file=multipartRequest.getFile("file");
        	InputStream fileStream;
    		try {
    			fileStream = file.getInputStream();
    			if(fileStream != null){
        			String upload_file_name = file.getOriginalFilename();//本地文件名称
        			String suffix_name = upload_file_name.substring(upload_file_name.indexOf(".")+1);//后缀名
        			//String new_file_name = PictureUtil.createFileName(suffix_name);//新文件名
        			String re_file_path = POIFileUtil.getFileName(upload_file_name,suffix_name,file_kind);//文件相对路径
        			String full_file_name = POIFileUtil.getAbFileNameByRepath(re_file_path); //绝对路径
        			Boolean is_success = PictureUtil.storeFile(fileStream, full_file_name);
        			if(is_success){
        				String file_id = daoPcProjectFile.saveFile(re_file_path,upload_file_name);
        				data_map = new NutMap();
        				data_map.put("code", 0);
        				data_map.put("msg", "上传成功!");
        				data_map.put("original_file_name", re_file_path); //文件原始名称
        				data_map.put("upload_file_name", upload_file_name);
        				data_map.put("file_id", file_id); //文件id
        				return data_map;
        			}
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	return new NutMap("code",1).addv("msg", "上传失败!");
	}
	
	
	
	

}
